/*
 * 评论区组件 - Comment Section Component
 * 实现评论展示、提交、折叠展开等功能
 */

import React, { useState, useEffect } from 'react';
import {
  Avatar,
  Button,
  Input,
  message,
  Empty,
  Divider,
  Spin
} from 'antd';
import {
  UserOutlined,
  MessageOutlined,
  SendOutlined
} from '@ant-design/icons';
import { getPostComments, addComment } from '../../../services/Post/api';
import { getAnonymousUserInfo } from '../../../services/AnonymousUser/api';
import { useUserIdentity } from '../../../hooks/useUserId';
import AnonymousUserInfoForm from '../../../components/AnonymousUserInfoForm';
import ReplyBox from '../../../components/ReplyBox';
import styles from './CommentSection.less';

const { TextArea } = Input;

interface CommentData {
  id: number;
  content: string;
  user_id: number;
  userId?: string;
  userName?: string;
  username?: string;
  userAvatar?: string;
  avatar?: string;
  create_time: string;
  createTime?: string;
  like_count: number;
  reply_count: number;
  parent_id: number;
  parentId?: number;
  replyToUsername?: string;
  reply_to_username?: string; // 后端返回的字段名（下划线）
  replyToUserId?: string;
  reply_to_user_id?: string; // 后端返回的字段名（下划线）
  children?: CommentData[];
  level?: number;
  post_id: number;
}

interface CommentSectionProps {
  postId: number;
  currentUserId: number;
  onCommentCountChange?: (count: number) => void;
}

interface CommentItemProps {
  comment: CommentData;
  postId: number;
  currentUserId: string;
  onDelete: () => void;
  onReply?: (commentId: number, username: string, replyToUserId: string) => void;
  level?: number;
}

const CommentItemComponent: React.FC<CommentItemProps> = ({
  comment,
  currentUserId,
  onDelete,
  onReply,
  level = 0,
}) => {

  const formatTime = (timeStr: string) => {
    try {
      const time = new Date(timeStr);
      return time
        .toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false,
        })
        .replace(/\//g, '-');
    } catch {
      return timeStr;
    }
  };

  const displayUserId = comment.userId?.toString() || comment.user_id?.toString();
  const isOwner = currentUserId === displayUserId;
  const displayName = comment.username || comment.userName || `用户${comment.user_id}`;
  const displayTime = comment.createTime || comment.create_time;
  const displayAvatar = comment.avatar || comment.userAvatar;
  const displayReplyToUsername = comment.reply_to_username || comment.replyToUsername;

  return (
    <div className={`${styles.commentItem} ${styles[`level-${level}`] || ''}`}>
      <Avatar
        src={displayAvatar}
        icon={<UserOutlined />}
        size={48}
        className={styles.avatar}
      />
      <div className={styles.commentContent}>
        <div className={styles.commentHeader}>
          <div className={styles.userInfo}>
            <span className={styles.username}>{displayName}</span>
            {displayReplyToUsername && (
              <>
                <span className={styles.replyArrow}> ▸ </span>
                <span className={styles.replyToUser}>
                  {displayReplyToUsername}
                </span>
              </>
            )}
          </div>
          <span className={styles.time}>{formatTime(displayTime)}</span>
          <Button
            type="text"
            size="small"
            icon={<MessageOutlined />}
            onClick={() =>
              onReply?.(comment.id, displayName, displayUserId || '')
            }
            className={styles.replyBtn}
          >
            回复
          </Button>
        </div>

        <div className={styles.commentText}>{comment.content}</div>
      </div>
    </div>
  );
};

// 扁平化评论数据的函数
const flattenComments = (
  comments: CommentData[],
  level = 0,
): Array<CommentData & { level: number }> => {
  const result: Array<CommentData & { level: number }> = [];

  comments.forEach((comment) => {
    result.push({ ...comment, level });
    const childComments = comment.children || [];
    if (childComments.length > 0) {
      // 所有回复都是同一层（level 1）
      result.push(...flattenComments(childComments, level > 0 ? level : 1));
    }
  });

  console.log(`📊 扁平化 ${comments.length} 条评论，总共 ${result.length} 条`, result);
  return result;
};

// 渲染评论列表和回复框的函数
const renderCommentsWithReply = (
  comments: Array<CommentData & { level: number }>,
  postId: number,
  userId: string,
  onDelete: () => void,
  onReply: (commentId: number, username: string, replyToUserId: string) => void,
  replyingTo: number | null,
  replyingUsername: string,
  onReplySubmit: (content: string) => void,
  onCancelReply: () => void,
) => {
  const elements = [];

  for (let i = 0; i < comments.length; i++) {
    const comment = comments[i];

    // 添加评论项
    elements.push(
      <CommentItemComponent
        key={comment.id}
        comment={comment}
        postId={postId}
        currentUserId={userId}
        onDelete={onDelete}
        onReply={onReply}
        level={comment.level}
      />,
    );

    // 检查是否需要在此处显示回复框
    if (replyingTo && comment.id === replyingTo) {
      const isTopLevelComment = comment.level === 0;
      const placeholder = isTopLevelComment
        ? '写下你的回复...'
        : `回复@${replyingUsername}：`;

      elements.push(
        <div key={`reply-${replyingTo}`} className={styles.replyBoxContainer}>
          <ReplyBox
            targetUsername={replyingUsername}
            onSubmit={onReplySubmit}
            onCancel={onCancelReply}
            placeholder={placeholder}
          />
        </div>,
      );
    }
  }

  return elements;
};

const CommentSection: React.FC<CommentSectionProps> = ({
  postId,
  currentUserId,
  onCommentCountChange
}) => {
  const [comments, setComments] = useState<CommentData[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [commentText, setCommentText] = useState('');
  const [replyingTo, setReplyingTo] = useState<number | null>(null);
  const [replyingUsername, setReplyingUsername] = useState<string>('');
  const [replyingToUserId, setReplyingToUserId] = useState<string | undefined>();
  const [canComment, setCanComment] = useState(true);
  const [showUserInfoForm, setShowUserInfoForm] = useState(false);
  const [userInfoData, setUserInfoData] = useState({
    name: '',
    email: '',
    link: '',
  });

  const identity = useUserIdentity();
  const userId = currentUserId?.toString() || '';

  // 检查匿名用户信息
  const checkAnonymousUserInfo = async () => {
    // 如果已登录，不需要检查
    if (identity.isLoggedIn) {
      setShowUserInfoForm(false);
      setCanComment(true);
      return;
    }

    // 检查localStorage中是否有信息
    const localName = localStorage.getItem('anonymousUserName');
    const localEmail = localStorage.getItem('anonymousUserEmail');
    const localLink = localStorage.getItem('anonymousUserLink');

    // 如果localStorage中邮箱存在且不为空，不需要请求后端和显示表单
    if (localEmail && localEmail.trim()) {
      setShowUserInfoForm(false);
      setCanComment(true);
      return;
    }

    // 如果没有userId，等待生成
    if (!userId) {
      return;
    }

    try {
      // 请求后端检查是否已填写
      const result = await getAnonymousUserInfo(userId);
      
      if (result.data.exists) {
        const { name, email, link } = result.data;
        
        // 如果后端有数据，同步到localStorage
        if (name && name.trim()) {
          localStorage.setItem('anonymousUserName', name);
        }
        if (email && email.trim()) {
          localStorage.setItem('anonymousUserEmail', email);
        }
        if (link && link.trim()) {
          localStorage.setItem('anonymousUserLink', link);
        }

        // 后端会自动生成name，所以只需要检查email是否为空
        if (!email || !email.trim()) {
          setShowUserInfoForm(true);
          setCanComment(false);
          setUserInfoData({ name: name || '', email: email || '', link: link || '' });
        } else {
          setShowUserInfoForm(false);
          setCanComment(true);
        }
      } else {
        // 后端不存在记录，显示表单
        setShowUserInfoForm(true);
        setCanComment(false);
        setUserInfoData({ name: '', email: '', link: '' });
      }
    } catch (error) {
      console.error('检查匿名用户信息失败:', error);
      // 出错时，如果localStorage没有邮箱信息，显示表单
      if (!localEmail || !localEmail.trim()) {
        setShowUserInfoForm(true);
        setCanComment(false);
        setUserInfoData({ name: localName || '', email: localEmail || '', link: localLink || '' });
      }
    }
  };

  // 表单提交成功后的回调
  const handleUserInfoSubmitSuccess = () => {
    setShowUserInfoForm(false);
    setCanComment(true);
    message.success('个人信息已完善，现在可以评论了！');
  };

  // 检查是否可以评论（实时监听）
  useEffect(() => {
    const checkCanComment = () => {
      if (identity.isLoggedIn) {
        setCanComment(true);
      } else {
        const localEmail = localStorage.getItem('anonymousUserEmail');
        setCanComment(!!localEmail && !!localEmail.trim());
      }
    };

    // 初始检查
    checkCanComment();

    // 监听storage事件
    window.addEventListener('storage', checkCanComment);
    
    // 定期检查（解决同一标签页内localStorage更新的问题）
    const intervalId = setInterval(checkCanComment, 500);

    return () => {
      window.removeEventListener('storage', checkCanComment);
      clearInterval(intervalId);
    };
  }, [identity.isLoggedIn]);

  // 当userId和identity准备好时，检查匿名用户信息
  useEffect(() => {
    if (userId) {
      checkAnonymousUserInfo();
    }
  }, [userId, identity.isLoggedIn]);

  const fetchComments = async () => {
    try {
      setLoading(true);
      const response = await getPostComments(postId);
      console.log('📝 评论数据（后端已构建树形结构）:', response.data);
      if (response.success) {
        // 后端已经返回树形结构，直接使用
        const treeComments = response.data || [];
        console.log('🌲 评论树:', treeComments);
        setComments(treeComments);
        // 递归计算总评论数
        onCommentCountChange?.(countAllComments(treeComments));
      } else {
        message.error('获取评论失败');
      }
    } catch (error) {
      console.error('❌ 获取评论失败:', error);
      message.error('获取评论失败');
    } finally {
      setLoading(false);
    }
  };

  // 递归计算所有评论数量（包括嵌套的回复）
  const countAllComments = (comments: CommentData[]): number => {
    let count = comments.length;
    comments.forEach(comment => {
      if (comment.children && comment.children.length > 0) {
        count += countAllComments(comment.children);
      }
    });
    return count;
  };


  useEffect(() => {
    fetchComments();
  }, [postId]);

  // 提交评论
  const handleSubmitComment = async () => {
    if (!canComment) {
      message.warning('请先完善您的邮箱信息才能评论');
      return;
    }

    if (!commentText.trim()) {
      message.warning('请输入评论内容');
      return;
    }

    if (!userId) {
      message.warning('用户ID获取失败，请刷新页面');
      return;
    }

    try {
      setSubmitting(true);
      const response = await addComment(postId, Number(userId), commentText.trim());
      if (response.success) {
        message.success('评论成功');
        setCommentText('');
        await fetchComments();
      } else {
        message.error('评论失败');
      }
    } catch (error) {
      message.error('评论失败');
    } finally {
      setSubmitting(false);
    }
  };

  // 开始回复
  const handleReply = (commentId: number, username: string, replyToUserId?: string) => {
    if (!canComment) {
      message.warning('请先完善您的邮箱信息才能回复');
      return;
    }
    setReplyingTo(commentId);
    setReplyingUsername(username);
    setReplyingToUserId(replyToUserId);
  };

  // 取消回复
  const handleCancelReply = () => {
    setReplyingTo(null);
    setReplyingUsername('');
    setReplyingToUserId(undefined);
  };

  // 提交回复
  const handleReplySubmit = async (content: string) => {
    if (!userId) {
      message.warning('用户ID获取失败，请刷新页面');
      return;
    }

    if (!replyingTo) {
      message.warning('回复目标不存在');
      return;
    }

    try {
      const response = await addComment(
        postId, 
        Number(userId), 
        content.trim(), 
        replyingTo,
        replyingToUserId ? Number(replyingToUserId) : undefined
      );
      if (response.success) {
        message.success('回复成功');
        handleCancelReply();
        await fetchComments();
      } else {
        message.error('回复失败');
      }
    } catch (error) {
      message.error('回复失败');
    }
  };

  return (
    <div className={styles.commentSection}>
      {/* 匿名用户信息表单 */}
      {showUserInfoForm && userId && (
        <div style={{ marginBottom: '16px' }}>
          <AnonymousUserInfoForm
            userId={userId}
            initialName={userInfoData.name}
            initialEmail={userInfoData.email}
            initialLink={userInfoData.link}
            onSubmitSuccess={handleUserInfoSubmitSuccess}
          />
        </div>
      )}

      {/* 评论输入框 */}
      <div className={styles.commentInput}>
        <div className={styles.inputWrapper}>
          <Avatar
            icon={<UserOutlined />}
            size={32}
            className={styles.inputAvatar}
          />
          <div className={styles.inputContent}>
            <TextArea
              value={commentText}
              onChange={(e) => setCommentText(e.target.value)}
              placeholder={canComment ? "写下你的评论..." : "请先完善邮箱信息才能评论"}
              autoSize={{ minRows: 2, maxRows: 4 }}
              className={styles.textArea}
              maxLength={500}
              disabled={!canComment}
            />
            <div className={styles.inputActions}>
              {!canComment && (
                <span className={styles.disabledTip}>
                  请先完善邮箱信息
                </span>
              )}
              <Button
                type="primary"
                size="small"
                icon={<SendOutlined />}
                loading={submitting}
                onClick={handleSubmitComment}
                disabled={!commentText.trim() || !canComment}
                className={styles.submitBtn}
                title={!canComment ? '请先完善邮箱信息' : ''}
              >
                发表评论
              </Button>
            </div>
          </div>
        </div>
      </div>

      <Divider className={styles.divider} />

      {/* 评论列表 */}
      <div className={styles.commentList}>
        {loading ? (
          <div className={styles.loadingContainer}>
            <Spin size="large" />
          </div>
        ) : comments.length === 0 ? (
          <Empty
            description="暂无评论"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        ) : (
          renderCommentsWithReply(
            flattenComments(comments),
            postId,
            userId,
            fetchComments,
            handleReply,
            replyingTo,
            replyingUsername,
            handleReplySubmit,
            handleCancelReply,
          )
        )}
      </div>
    </div>
  );
};

export default CommentSection;
